<template>
	<view class="create_order">
		<view class="buzou">
			<!-- 基本用法 -->
			<uni-steps 
			:options="[{title: '客户下单'}, {title: '填写订单'}, {title: '发布订单'}]" 
			:active="active"></uni-steps>
		</view>
		<view class="order_form">
			<view class="address" @click="choseAddress" >
				<view class="info" v-if="defaultAddress.id">
					<view class="left-icon">
						<text class="iconfont icon-location"></text>
					</view>
					<view class="info_txt">
						<view class="add_info">
							{{ defaultAddress.nativenative }} {{ defaultAddress.address }}
						</view>
						<view class="user_info">
							<view class="name">
								{{ defaultAddress.name }}
							</view>
							<view class="phone">
								{{ defaultAddress.phone }}
							</view>
						</view>
					</view>
				</view>
				<view class="tip" v-else  style="text-align: center;">
					<text class="iconfont icon-dingwei"></text>选择地址
				</view>
				<view class="icon" style="margin-top: 5rpx;">
					<van-icon name="arrow" />
				</view>
			</view>
			
			<!-- <view class="order_items">
				
				<button type="primary" @click="itemShow = true" >{{ itemName ? itemName : "选择类目"}}</button>
			</view> -->
			<van-field
			    :value="shopnum"
			    center
			    clearable
				left-icon="location"
				disabled
			    label="附近商家"
			    placeholder=""
			    use-button-slot
			  >
			    <!-- <van-button slot="button" size="mini" type="primary" :disabled="itemDisabled" @click="itemShow = true">服务类目</van-button> -->
			  </van-field>
			<van-field
			    :value="itemName"
			    center
			    clearable
				left-icon="orders-o"
				disabled
			    label="服务类目"
			    placeholder="请选择服务类目"
			    use-button-slot
			  >
			    <!-- <van-button slot="button" size="mini" type="primary" :disabled="itemDisabled" @click="itemShow = true">服务类目</van-button> -->
			  </van-field>
			
			<van-field label="服务时间" :value="currentDate" left-icon="clock-o" use-button-slot>
				<van-button slot="button" size="mini" type="primary" @click="choseTime">选择时间</van-button>
			</van-field>
			<!-- <van-field label="服务面积" 
			:value="orderData.acreage" 
			type="number" 
			maxlength="3"
			left-icon="location-o" clearable @change="acrChange" placeholder="选填"></van-field> -->
			<van-field label="备注" :value="orderData.bei" :disabled="disabled" clearable @change="beiChange" left-icon="comment-o" use-button-slot placeholder="服务需求">
				<van-button slot="button" size="mini" type="primary" v-if="!orderData.bei" @click="getAudio">{{ voice }}</van-button>
				<van-button slot="button" size="mini" icon="play-circle-o"  v-if="audioSrc" type="success" @click="onPlays">播放</van-button>
			</van-field>
		</view>
		<view class="btn_box">
			<button type="primary" @click="getSetting">发布订单</button>
		</view>
		<!-- 时间选择器 -->
		<view class="time_chose" v-if="timeShow">
			<van-datetime-picker
			  type="datetime"
			  :value="currentDate"
			  :min-date="minDate"
			  @confirm="onConfirm"
			  
			/>
		</view>
		 
		 <!-- item -->
		 <van-picker
		   show-toolbar
		   title="选择类目"
		   v-if="itemShow"
		   :columns="options"
		   @cancel="itemCancel"
		   @change="getItem"
		   @confirm="itemConfirm"
		 />
	</view>
</template>

<script>
	// import InputTemplate from "@/components/public/order/InputTemplate.vue"
	import uniSteps from '@/components/uni-steps/uni-steps.vue'
	import {getLocaltion, timeFormat} from "@/post.js"
	var audioPlayer = uni.createInnerAudioContext()
	const voiceReciver = uni.getRecorderManager();
	export default {
		data() {
			return {
				orderData: {
					remark: "",
					category: "2",
					acreage: "",
				},	
				timeShow: false,
				active: 1,
				voice: "录音",
				disabled: false,
				addressList: [],
				defaultAddress: "",
				// type: "2",
				minDate: new Date().getTime(),
				currentDate:timeFormat(new Date().getTime()),
				itemShow: false,
				itemName:"",
				shopnum: "0",
				itemDisabled: false,
				access_token: '',
			}
		},
		components: {
			// InputTemplate,
			uniSteps,
		},
		computed: {
			audioSrc() {
				return this.$store.state.msgAudio
			},
			navbar() {
				return this.$store.state.navbar
			},
			options() {
				 let arr = []
				 let data = this.navabr
					this.navbar.forEach( el => {
						arr.push({
							text:el.name,
							id: el.id
						})
					})
				return arr

			},
			token() {
				return this.$store.state.token
			},
			defAddress() {
				return this.$store.state.defaultAddress ? this.$store.state.defaultAddress : ""
			},
			servicetime() {
				return this.currentDate
			},
			type() {
				if(this.audioSrc) {
					return "1"
				} else {
					return  "2"
				}
			},
			ChoseServer() {
				return this.$store.state.ServerName
			},
			realcity() {
				return this.$store.state.cityInfo.city
			},
			sid() {
				return this.$store.state.sid;
			}
		},
		onLoad( e ) {
			if(this.ChoseServer.name) {
				this.itemName = this.ChoseServer.name
			}
		},
		onShow() {
			this.getAccess_token()
			this.getShopList()
			this.getAddress()
			this.hasAudio()
			this.reflash_token()
		},
		methods: {
			// 获取商家
			async getShopList( city ) {
				let self = this
				console.log(this.city)
				let res = await this.$Request("POST", "/Index/worknum", { city: this.realcity })
				console.log(res)
				let code = res.data.code
				if(code == 200) {
					let num = res.data.data
					this.shopnum = `附近${num}家商家为您服务`
				}
				
			},
			// 选择日期
			// onInput( e ) {
			// 	this.currentDate = e.detail
			// },
			onConfirm(e) {
				
				let time = timeFormat(e.detail)
				this.timeShow = false
				console.log(time);
				this.currentDate = time
			},
			choseTime() {
				this.timeShow = true
			},
			// 选择地址
			choseAddress() {
				uni.navigateTo({
					url:"/pages/addresslist/addresslist"
				})
			},
			// 获取地址列表
			async getAddress() {
				let res = await this.$Request("POST","/Index/address", { token: this.token })
				// console.log(res.data.data);
				let self = this
				this.addressList = res.data.data
				if(this.defAddress.phone) {
					this.defaultAddress = this.defAddress
				} else {
					this.addressList.forEach(el => {
						if(el.tacitly == 1) {
							self.defaultAddress = el
						}
					})
				}
			},
			// input change事件
			beiChange( e ) {
				console.log(e.detail);
				 this.orderData.remark = e.detail
			},
			acrChange( e ) {
				let reg =/\D/g
				this.orderData.acreage = e.detail
				this.orderData.acreage = this.orderData.acreage.replace(reg, "")
				// console.log(this.orderData.acreage );
			},
			itemChange(e) {
				//console.log(e);
				this.orderData.items = e
			},
			localChange( e ) {
				this.orderData.local = e
			},
			//  组件按钮事件
			emitEvent( e ) {
				console.log(e);
			},
			// 检验数据
			checkData() {
				let { category, acreage, remark } = this.orderData
				
				if(!category) {
					uni.showToast({
						title: "请选择服务项目",
						icon:"loading"
					})
					return false
				} else if(!remark && this.type == 2 || this.type == 1 && !this.audioSrc) {
					uni.showToast({
						title: "请留言或录下服务内容",
						icon:"loading"
					})
					return false
				} else {
					return true
				}
			},
			// 发布订单 
			async showData() {
				let self = this
				let area = this.defaultAddress.id
				if(!area) {
					uni.showToast({
						title: "请选择地址",
						icon: "loading"
					})
					return false
				}
				let {category, acreage, remark} = this.orderData
				// console.log(this.type);
					if(this.type == 1 ) {
						let data = {
							token: this.token,
							category,
							acreage: acreage ? acreage : "0",
							servicetime:this.currentDate,
							area,
							type: this.type
						}
						if(this.ChoseServer.id) {
							data.category = this.ChoseServer.id
							data.pid = this.ChoseServer.pid
						}
						// console.log(data);
						uni.uploadFile({
							url:`${self.$Request_Url}/order/indent`,
							filePath: self.audioSrc,
							name: "name",
							formData: data,
							success( res ) {
								console.log("2");
								console.log(res);
								let str = JSON.parse(res.data)
								let code = str.code
								if(code == 202) {
									uni.showToast({
										title:"发布成功",
										icon: "success"
									})
									self.sendMsg( res.data.data )
									setTimeout(() => {
										uni.switchTab({
											url:"/pages/index/index"
										})
									}, 2000)
								}
							}
						})
					} else {
						let data = {
							token: this.token,
							category,
							acreage: acreage ? acreage : "0",
							servicetime:this.currentDate,
							area,
							remark: remark ? remark : "无备注",
							type: this.type
						}
						if(this.ChoseServer.id) {
							data.category = this.ChoseServer.id
							data.pid = this.ChoseServer.pid
						}
						
						uni.request({
							url: `${self.$Request_Url}/order/indent`,
							method:"POST",
							data: data,
							success( res ) {
								console.log("data");
								console.log(res);
								let code = res.data.code 
								if(code == 202) {
									uni.showToast({
										title:"发布成功",
										icon: "success"
									})
									 self.sendMsg( res.data.data )
									setTimeout(() => {
										uni.switchTab({
											url:"/pages/index/index"
										})
									}, 2000)
								}
							}
						})
					}
			
			},
			// 录音界面
			getAudio() {
				uni.navigateTo({
					url: "/pages/audio/audio"
				})
			},
			// 是否是电话
			isPhone() {
				let isMatch = this.$isPhone(this.orderData.phone)
				if(!isMatch) {
					uni.showToast({
						title: "手机号码格式错误",
						icon:"loading"
					})
					return false
				} else {
					return true
				}
			},
			// 是否有录音
			hasAudio() {
				// console.log(this.audioSrc);
				if(this.audioSrc) {
					audioPlayer.src = this.audioSrc
					this.disabled = true
				} else {
					audioPlayer.src = ""
					this.disabled = false
				}
			},
			// onPlay
			onPlays() {
				console.log(this.audioSrc);
				audioPlayer.play()
			},
			// item
			itemCancel() {
				this.itemShow = false
			},
			// 以及类目变化是获取二级类目
			getItem( e ) {
				console.log(e);

			},
			itemConfirm(e) {
				// console.log(e);
				this.$store.commit("getServerName", "")
				this.itemName = e.detail.value.text
				this.orderData.category = e.detail.value.id
				this.$store.commit("getServerName", { name: this.itemName, id: this.orderData.category })
				this.itemShow = false
			},
			// 获取订阅消息授权
			getSetting() {
				let self = this
				uni.getSetting({
					withSubscriptions: true,
					success( res ) {
						let isauth = res.authSetting["scope.subscribeMessage"]
						
										// 用户同意授权
										wx.requestSubscribeMessage({
										  tmplIds: [
											  '-EmYCJVoB59CJtCx892Q6HF5D-K9PeTQaWgKDvPS4D4',
											  'fxviPJF4R7JGFzpRR8d2JiZJu7Sucm7_kYzXOGDlv_w',
											  '7wxsbVcGzkoQwRb3NWohsj6BgWfs19EI1kCAGgbIOSM'
											  ],
										  success (res) {
											  // console.log(res);
											  let msg = res.errMsg == "requestSubscribeMessage:ok"
											  if(msg) {
												   self.showData()
											  } else {
												  return false 
											  }
										  },
										  fail(err) {
											  console.log(err);
										  }
										})
						},
				})
				
			},
			// 下单成功后 发送消息
			sendMsg( data ) {
				let self = this
				let reg = /^(http)/
				let isradio = reg.test(data.remark)
				let mark = ""
				if(isradio) {
					mark = "音频"
				} else {
					mark = data.remark
				}
				uni.request({
					url: `https://www.awoojing.club/admin/sendMsg`,
					method: "POST",
					data: {
						touser: `${self.sid.openid}`,
						access_token: `${self.access_token}`,
						page: '/pages/index/index',
						lang: 'zh_CN',
						data: {
						  time1: {
							value: `${data.servicetime}`
						  },
						  thing2: {
							value: `${mark}`,
						  },
						  thing7: {
							value: `${data.name}`
						  },
						  thing9: {
							value: `${data.address}`
						  },
						  time10: {
						  	 value: `${data.addtime}`
						  },
						},
						templateId: '-EmYCJVoB59CJtCx892Q6HF5D-K9PeTQaWgKDvPS4D4',
						miniprogramState: 'developer'
					},
					success( res ) {
						console.log(res);
					},
					fail( err ) {
						console.log(err);
					}
				})
				
					
			},
			//  进入当前页面后获取access_token
			getAccess_token() {
				let self = this
				uni.request({
					url: "https://www.awoojing.club/admin/getAccess_token",
					method:"POST",
					data: {},
					success(res) {
						// console.log(res);
						if(res.data.code == 200) {
							self.access_token = res.data.data
						}
					}
				})
				
			},
			// 定时刷新access_token
			reflash_token() {
				let self = this 
				setInterval(() => {
					self.getAccess_token()
				}, 1000 * 60 * 10)
			},
		},
		destroyed() {
			this.$store.commit("getDefaultAddress", "")
			this.$store.commit("getMsgAudio", "")
		},
		
	}
</script>

<style scoped lang="scss">
	.btn_box {
		width: 100%;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}
	.buzou {
		width: 100%;
		box-sizing: border-box;
		padding: 20rpx 0;
	}
	.order_form {
		width: 100%;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
	}
	.address {
		// text-align: center;
		width: 100%;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		box-sizing: border-box;
		border-top: 1px solid #f2f2f2;
		border-bottom: 1px solid #f2f2f2;
		.tip {
			// font-size: 24rpx;
			width: 600rpx;
			line-height: 32rpx;
		}
		.info {
			flex: 1;
			display: flex;
			align-items: center;
			font-size: 26rpx;
			padding-left: 10rpx;
			.info_txt {
				width: 100%;
				padding: 0 20rpx;
			}
			.left_icon {
				color: #007AFF;
				text-align: center;
			}
			.add_info {
				flex: 1;
				
			}
			.user_info {
				width: 100%;
				display: flex;
				align-items: center;
				.phone {
					margin-left: 20rpx;
				}
			}
		}
		.icon {
			width: 50rpx;
			color: #007AFF;
		}
	}
</style>
